package com.mini.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mini.client.WehubAdminClient;
import com.mini.conditon.TeacherCondition;
import com.mini.config.CheckLogin;
import com.mini.constant.AllocationLevel;
import com.mini.model.BusinessTeacherInfo;
import com.mini.model.BusinessTeacherWechatInfo;
import com.mini.req.CorpWxInfoREQ;
import com.mini.req.SyncTeacherREQ;
import com.mini.req.TeacherWechatREQ;
import com.mini.service.BusinessTeacherInfoService;
import com.mini.service.BusinessTeacherWechatInfoService;
import com.mini.service.MiniAdminService;
import com.mini.util.MatcherRule;
import com.mini.vo.BusinessResult;
import com.mini.vo.CommonResultMessage;
import com.mini.vo.PageResultVO;
import com.mini.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author zhangxiaobin
 * @title: BusinessTeacherController
 * @description: TODO
 * @date 2019/10/2716:08
 */
@RestController
@RequestMapping("/teacher")
@Slf4j
@Api(tags = "运营专员、老师相关(不对外提供接口，数据操作通过mini-lesson-business)")
public class BusinessTeacherController extends BaseController {

    @Autowired
    private BusinessTeacherInfoService teacherInfoService;

    @Autowired
    private BusinessTeacherWechatInfoService teacherWechatInfoService;

    @Autowired
    private MiniAdminService miniAdminService;

    @Autowired
    private WehubAdminClient wehubAdminServer;

    private static final String TEACHER_QR_IMG_PATH = "teacher/qr/";


    @CheckLogin
    @GetMapping("/disableTeacher")
    @ApiOperation(value = "禁用运营专员", notes = "禁用运营专员",hidden = true)
    public BusinessResult disableTeacher(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                         @ApiParam(value = "运营专员id", required = true) @RequestParam Long teacherId,
                                         @ApiParam(value = "操作人id", required = true) @RequestParam Long updateUserId) {
        log.info("禁用运营专员 teacherId = {} , updateUserID = {} ", teacherId, updateUserId);
        asyncTaskManager.getExecutor().submit(new Runnable() {
            @Override
            public void run() {
                BusinessTeacherInfo teacherInfo = teacherInfoService.findByTeacherId(teacherId);
                if (teacherInfo != null) {
                    teacherInfo.setStates(1);
//                    teacherInfo.setAddWechatNum(0);
                    teacherInfo.setUpdateUser(updateUserId);
                    teacherInfo.setUpdateTime(new Date());
                    teacherInfoService.save(teacherInfo);
                    //禁用weihub相关数据
//                    enableOrdisableWehubAbout(1, teacherId, updateUserId, null, null);
                    //禁用企业微信相关数据
                    teacherWechatInfoService.deleteAllCorpInfo(teacherId);

                    //删除排班数据
                    //TODO 删除传统排班
//                    teacherSchedulingInfoService.deleteByTeacherId(teacherId, teacherInfo.getGroupId(), teacherInfo.getDeptId(), teacherInfo.getWorkRoomId(), null, null, null);

                    //解绑微信号
                    teacherWechatInfoService.deleteTeacherAllWechatNo(teacherId);
                }
            }
        });
        return BusinessResult.createSuccessInstance(null);
    }

    @CheckLogin
    @GetMapping("/disableTeacherAccount")
    @ApiOperation(value = "禁用运营专员账号", notes = "禁用运营专员账号")
    public BusinessResult disableTeacherAccount(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                                @ApiParam(value = "运营专员id",required = true)@RequestParam Long teacherId,
                                                @ApiParam(value = "操作人id",required = true)@RequestParam Long updateUserId){
        log.info("禁用运营专员账号 teacherId = {} , updateUserID = {} ",teacherId,updateUserId);
        asyncTaskManager.getExecutor().submit(new Runnable() {
            @Override
            public void run() {

                BusinessTeacherInfo teacherInfo = teacherInfoService.findByTeacherId(teacherId);
                if(teacherInfo != null){
                    teacherInfo.setStates(1);
//                    teacherInfo.setAddWechatNum(0);
                    teacherInfo.setUpdateUser(updateUserId);
                    teacherInfo.setUpdateTime(new Date());
                    teacherInfo.setAccountStatus(1);
                    teacherInfoService.save(teacherInfo);
                    //禁用weihub相关数据
//                    enableOrdisableWehubAbout(1,teacherId,updateUserId,null,null);
                    //禁用企业微信相关数据
                    teacherWechatInfoService.deleteAllCorpInfo(teacherId);
                    //删除排班数据
                    //TODO 删除传统排班
//                    teacherSchedulingInfoService.deleteByTeacherId(teacherId,teacherInfo.getGroupId(),teacherInfo.getDeptId(),teacherInfo.getWorkRoomId(),null,null,null);

                    //解绑微信号
                    teacherWechatInfoService.deleteTeacherAllWechatNo(teacherId);
                }
            }
        });
        return BusinessResult.createSuccessInstance(null);
    }


    @CheckLogin
    @GetMapping("/enableTeacher")
    @ApiOperation(value = "启用运营专员", notes = "启用运营专员",hidden = true)
    public BusinessResult enableTeacher(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                        @ApiParam(value = "运营专员id", required = true) @RequestParam Long teacherId,
                                        @ApiParam(value = "操作人id", required = true) @RequestParam Long updateUserId) {
        log.info("启用运营专员 teacherId = {} , updateUserID = {} ", teacherId, updateUserId);

        BusinessTeacherInfo teacherInfo = teacherInfoService.findByTeacherId(teacherId);
        if (teacherInfo != null) {
            List<BusinessTeacherWechatInfo> wechatInfos = teacherWechatInfoService.findByTeacherId(teacherId, null);
            if (CollectionUtils.isEmpty(wechatInfos)) {
                return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "未查询到该运营人员对应的微信信息，请确认！");
            }
            teacherInfo.setStates(0);
//            teacherInfo.setAddWechatNum(0);
            teacherInfo.setUpdateUser(updateUserId);
            teacherInfo.setUpdateTime(new Date());
            teacherInfoService.save(teacherInfo);
            for (BusinessTeacherWechatInfo teacherWechatInfo : wechatInfos) {
                teacherWechatInfo.setStates(0);
                teacherWechatInfo.setUpdateTime(new Date());
                teacherWechatInfo.setUpdateUser(updateUserId);
                teacherWechatInfoService.save(teacherWechatInfo);
            }

        }

        return BusinessResult.createSuccessInstance(null);
    }

    @CheckLogin
    @GetMapping("/enableTeacherAccount")
    @ApiOperation(value = "启用运营专员账号", notes = "启用运营专员账号")
    public BusinessResult enableTeacherAccount(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                               @ApiParam(value = "运营专员id",required = true)@RequestParam Long teacherId,
                                               @ApiParam(value = "操作人id",required = true)@RequestParam Long updateUserId){
        log.info("启用运营专员账号 teacherId = {} , updateUserID = {} ",teacherId,updateUserId);

        BusinessTeacherInfo teacherInfo = teacherInfoService.findByTeacherId(teacherId);
        if(teacherInfo != null){
            teacherInfo.setUpdateUser(updateUserId);
            teacherInfo.setUpdateTime(new Date());
            teacherInfo.setAccountStatus(0);
//            teacherInfo.setAddWechatNum(0);
            teacherInfoService.save(teacherInfo);
        }

        return BusinessResult.createSuccessInstance(null);
    }

    @CheckLogin
    @PostMapping("/saveTeacher")
    @ApiOperation(value = "保存运营专员", notes = "保存运营专员",hidden = true)
    public BusinessResult saveTeacher(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                      @RequestBody SyncTeacherREQ syncTeacherREQ) {
        log.info("保存运营专员 params = {} ", JSON.toJSONString(syncTeacherREQ));

        UserVO loginUser = getLoginUser(Authorization);

        Long teacherId = syncTeacherREQ.getTeacherId();
        List<String> errorMsgs = new ArrayList<>();
        if (teacherId == null || 0 == teacherId.intValue()) {
            errorMsgs.add("teacherId 值为空");
        }
        Long newGroupId = syncTeacherREQ.getGroupId();
        if (newGroupId == null || 0 == newGroupId.intValue()) {
            errorMsgs.add("groupId 值为空");
        }
        if (syncTeacherREQ.getCreateUser() == null || 0 == syncTeacherREQ.getCreateUser().intValue()) {
            errorMsgs.add("createUser 值为空");
        }
        if (StringUtils.isBlank(syncTeacherREQ.getTeacherName())) {
            errorMsgs.add("teacherName 值为空");
        }
        if (errorMsgs.size() > 0) {
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, JSON.toJSONString(errorMsgs));
        }
        String allocationLevel = syncTeacherREQ.getAllocationLevel();
        String oldAllocationLevelVal = "";
        BusinessTeacherInfo teacherInfo = teacherInfoService.findByTeacherId(teacherId);
        boolean updateAllocationLevel = false;
        boolean initAllocationLevel = false;
        if (teacherInfo == null) {
            teacherInfo = new BusinessTeacherInfo();

            teacherInfo.setAddWechatNum(0);
            teacherInfo.setPbStates(Objects.isNull(syncTeacherREQ.getPbStates())?0:syncTeacherREQ.getPbStates());
            teacherInfo.setStates(Objects.isNull(syncTeacherREQ.getStates())?1:syncTeacherREQ.getStates());
            teacherInfo.setOrders(Objects.isNull(syncTeacherREQ.getOrders())?teacherId.intValue():syncTeacherREQ.getOrders());
            teacherInfo.setCreateTime(Objects.isNull(syncTeacherREQ.getCreateTime())?new Date():syncTeacherREQ.getCreateTime());
            teacherInfo.setUpdateTime(Objects.isNull(syncTeacherREQ.getUpdateTime())?new Date():syncTeacherREQ.getUpdateTime());
            teacherInfo.setCreateUser(Objects.isNull(syncTeacherREQ.getCreateUser())?loginUser.getId():syncTeacherREQ.getCreateUser());
            teacherInfo.setUpdateUser(Objects.isNull(syncTeacherREQ.getUpdateUser())?loginUser.getId():syncTeacherREQ.getUpdateUser());
            teacherInfo.setChangeDeptTime(Objects.isNull(syncTeacherREQ.getChangeDeptTime())?new Date():syncTeacherREQ.getChangeDeptTime());
            teacherInfo.setAccountStatus(Objects.isNull(syncTeacherREQ.getAccountStatus())?0:syncTeacherREQ.getAccountStatus());
            if (StringUtils.isNotBlank(allocationLevel)) {
                teacherInfo.setAllocationLevel(AllocationLevel.valueOf(allocationLevel));
            } else {
                allocationLevel = AllocationLevel.A.toString();
                teacherInfo.setAllocationLevel(AllocationLevel.A);
            }
            initAllocationLevel = true;
            updateAllocationLevel = true;
        } else {
            Long oldGroupId = teacherInfo.getGroupId();
            Long oldDeptId = teacherInfo.getDeptId();
            Long oldWorkRoomId = teacherInfo.getWorkRoomId();
            if (!(newGroupId.equals(oldGroupId))) {
                teacherInfo.setChangeDeptTime(new Date());

                //TODO 禁止排班
//                teacherSchedulingInfoService.deleteByTeacherId(teacherId, oldGroupId, oldDeptId, oldWorkRoomId, newGroupId, syncTeacherREQ.getDeptId(), syncTeacherREQ.getWorkRoomId());
            }
            AllocationLevel oldAllocationLevel = teacherInfo.getAllocationLevel();
            if (StringUtils.isNotBlank(allocationLevel)) {
                AllocationLevel newAllocationLevel = AllocationLevel.valueOf(allocationLevel);
                if (oldAllocationLevel == null) {
                    teacherInfo.setAllocationLevel(AllocationLevel.valueOf(allocationLevel));
                } else if (oldAllocationLevel != newAllocationLevel) {
                    //修改等级
                    teacherInfo.setAllocationLevel(newAllocationLevel);
                    updateAllocationLevel = true;
                    oldAllocationLevelVal = oldAllocationLevel.toString();
                }
            }

            teacherInfo.setUpdateTime(Objects.isNull(syncTeacherREQ.getUpdateTime())?new Date():syncTeacherREQ.getUpdateTime());
            teacherInfo.setUpdateUser(Objects.isNull(syncTeacherREQ.getUpdateUser())?loginUser.getId():syncTeacherREQ.getUpdateUser());

        }
        teacherInfo.setGroupName(syncTeacherREQ.getGroupName());
        teacherInfo.setTeacherLoginName(syncTeacherREQ.getLoginUserName());
        teacherInfo.setTeacherId(teacherId);
        teacherInfo.setTeacherName(syncTeacherREQ.getTeacherName());
        teacherInfo.setGroupId(newGroupId);
        teacherInfo.setDeptId(syncTeacherREQ.getDeptId());
        teacherInfo.setDeptName(syncTeacherREQ.getDeptName());
        teacherInfo.setWorkRoomId(syncTeacherREQ.getWorkRoomId());
        teacherInfo.setWorkRoomName(syncTeacherREQ.getWorkRoomName());
        teacherInfo.setSkuId(syncTeacherREQ.getSkuId());
        teacherInfo.setSkuName(syncTeacherREQ.getSkuName());
        teacherInfoService.save(teacherInfo);
        if (updateAllocationLevel) {
            String operationDesc = "设置等级，" + syncTeacherREQ.getTeacherName() + " 等级由 " + oldAllocationLevelVal + " 调到 " + allocationLevel;
            if (initAllocationLevel) {
                operationDesc = "设置等级，" + syncTeacherREQ.getTeacherName() + " 初始化等级 " + allocationLevel;
            }
            //TODO 排班操作日志
//            teacherSchedulingLogInfoService.recordOperation(teacherId, loginUser.getId(), loginUser.getNickname(), loginUser.getUsername(), operationDesc, 1);
        }
        return BusinessResult.createSuccessInstance(teacherInfo);

    }


    @CheckLogin
    @ApiOperation(value = "运营专员二维码信息，微信号修改", notes = "运营专员二维码信息，微信号修改",hidden = true)
    @PostMapping(value = "/updateTeacherQR")
    public BusinessResult updateTeacherQR(@RequestHeader String Authorization,
                                          @RequestBody SyncTeacherREQ syncTeacherREQ) {
        log.info("updateTeacherQR params = {} ", JSON.toJSONString(syncTeacherREQ));
        List<String> errormsg = new ArrayList<>();

        String wxId = syncTeacherREQ.getWxId();
        String wxNewId = syncTeacherREQ.getWxNewId();
        Long teacherId = syncTeacherREQ.getTeacherId();
        if (StringUtils.isBlank(syncTeacherREQ.getQrUrl())) {
            errormsg.add("QRUrl 为空");
        }
        if (StringUtils.isBlank(wxId)) {
            errormsg.add("wxId 为空");
        }
        if (StringUtils.isBlank(wxNewId)) {
            errormsg.add("wxNewId 为空");
        }
        if (teacherId.intValue() == 0) {
            errormsg.add("teacherId 值错误");
        }
        if (syncTeacherREQ.getUseType() == null) {
            errormsg.add("useType 值错误");
        }

        Long wxNoUseStates = teacherWechatInfoService.countByWxNoAndTeacherIdNot(wxNewId, teacherId);
        if (wxNoUseStates != null && wxNoUseStates.intValue() > 0) {
            errormsg.add("该微信号【" + wxNewId + "】已经绑定了飞天账号");
        }
        if (errormsg != null && errormsg.size() > 0) {
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, JSON.toJSONString(errormsg));
        }

        BusinessTeacherInfo teacherInfo = teacherInfoService.findByTeacherId(teacherId);
        if (teacherInfo == null) {
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "运营专员信息不存在");
        }
        teacherInfoService.saveWechat(teacherInfo, syncTeacherREQ);
        return BusinessResult.createSuccessInstance(null);
    }

    @CheckLogin
    @ApiOperation(value = "禁用启用微信号", notes = "禁用启用微信号",hidden = true)
    @GetMapping(value = "/wechatStates")
    public BusinessResult updateTeacherQR(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                          @ApiParam(value = "运营专员id", required = true) @RequestParam Long teacherId,
                                          @ApiParam(value = "状态 0启用 1禁用", required = true) @RequestParam Integer states,
                                          @ApiParam(value = "微信号", required = true) @RequestParam String wechatNo) {

        log.info("wechatStates teacherId = {},states={}, wechatNo={}", teacherId, states, wechatNo);
        List<String> errormsg = new ArrayList<>();

        if (!(states.equals(1)) && !(states.equals(0))) {
            errormsg.add("action参数值错误");
        }
        BusinessTeacherInfo teacherInfo = teacherInfoService.findByTeacherId(teacherId);
        if (teacherInfo == null) {
            errormsg.add("运营专员信息不存在");
        }

        if (errormsg != null && errormsg.size() > 0) {
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, JSON.toJSONString(errormsg));
        }

        if (states.equals(1)) {
            List<BusinessTeacherWechatInfo> canUseByTeacherId = teacherWechatInfoService.findCanUseWechatByTeacherId(teacherId, null);
            if (canUseByTeacherId.size() == 1) {
                String wxNo = canUseByTeacherId.get(0).getWxNo();
                if (wxNo.equalsIgnoreCase(wechatNo)) {
                    return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "至少保留一个可用的微信");
                }
            }
        }
        teacherWechatInfoService.updateWechatNoStates(teacherId, wechatNo, states, teacherInfo);
        return BusinessResult.createSuccessInstance(null);
    }

    @CheckLogin
    @ApiOperation(value = "批量解绑微信号", notes = "批量解绑微信号",hidden = true)
    @PostMapping(value = "{teacherId}/deleteWechatNo")
    public BusinessResult deleteWechatNos(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                          @ApiParam(value = "运营专员id", required = true) @PathVariable("teacherId") Long teacherId,
                                          @ApiParam(value = "微信号", required = true) @RequestBody TeacherWechatREQ wechatREQ) {


        log.info("deleteWechatNos teacherId = {},params={}", teacherId, JSON.toJSONString(wechatREQ));
        List<String> errormsg = new ArrayList<>();

        if (Objects.isNull(wechatREQ)) {
            errormsg.add("参数错误");
        }
        BusinessTeacherInfo teacherInfo = teacherInfoService.findByTeacherId(teacherId);
        if (Objects.isNull(teacherInfo)) {
            errormsg.add("运营专员信息不存在");
        }
        if (CollectionUtils.isEmpty(wechatREQ.getWechatList())) {
            errormsg.add("微信号为空");
        }

        if (errormsg != null && errormsg.size() > 0) {
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, JSON.toJSONString(errormsg));
        }

        wechatREQ.getWechatList().forEach(wechar -> {
            teacherWechatInfoService.deleteCorpInfo(wechar);
        });

        boolean empty = teacherWechatInfoService.deleteTeacherWechatNo(teacherId, wechatREQ.getWechatList());
        if (empty) {
            teacherInfo.setStates(1);
//            teacherInfo.setAddWechatNum(0);
            teacherInfo.setUpdateUser(wechatREQ.getUpdateUserId());
            teacherInfo.setUpdateTime(new Date());
            //TODO 取消排班
//            teacherSchedulingInfoService.deleteByTeacherId(teacherId, teacherInfo.getGroupId(), teacherInfo.getDeptId(), teacherInfo.getWorkRoomId(), null, null, null);
            teacherInfoService.save(teacherInfo);
            enableOrdisableWehubAbout(1, teacherId, wechatREQ.getUpdateUserId(), null, null);
        } else {
            wechatREQ.getWechatList().forEach(wechar -> {
                enableOrdisableWehubAbout(1, teacherId, wechatREQ.getUpdateUserId(), null, wechar);
            });
        }

        return BusinessResult.createSuccessInstance(null);
    }


    @CheckLogin
    @GetMapping("/{teacherId}")
    @ApiOperation(value = "查询专员信息，包含所有的微信", notes = "查询专员信息，包含所有的微信")
    public BusinessResult<BusinessTeacherInfo> getTeacherInfoByTeacherId(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                                                         @ApiParam(value = "运营专员id", required = true) @PathVariable Long teacherId,
                                                                         @ApiParam(value = "运营专员id", required = false, defaultValue = "0")
                                                                         @RequestParam(required = false, defaultValue = "0") Integer deptFullName) {

        BusinessTeacherInfo teacherInfo = teacherInfoService.findByTeacherId(teacherId);
        if (teacherInfo != null && teacherInfo.getGroupId() != null && 1 == deptFullName.intValue()) {
            teacherInfo.setDeptFullName(miniAdminService.getDeptFullName(teacherInfo.getGroupId()));
        }
        if (teacherInfo != null) {
            teacherInfo.setWechatInfos(teacherWechatInfoService.findByTeacherId(teacherInfo.getTeacherId(), null));
        }

        return BusinessResult.createSuccessInstance(teacherInfo);
    }

    @CheckLogin
    @GetMapping("/getMyTeacherLieBianWeChat")
    @ApiOperation(value = "查询专员信息及裂变微信号", notes = "查询专员信息及裂变微信号")
    public BusinessResult<BusinessTeacherInfo> getMyTeacherLieBianWeChat(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                                                         @ApiParam(value = "运营专员id", required = true) @RequestParam Long teacherId,
                                                                         @ApiParam(value = "微信号类型 0:个人微信 2：企业微信", required = true) @RequestParam Integer useType,
                                                                         @RequestParam(required = false, defaultValue = "0") Integer deptFullName) {
        List<String> errormsg = new ArrayList<>();

        if (Objects.isNull(teacherId)) {
            errormsg.add("参数错误");
        }
        if (Objects.isNull(useType)) {
            errormsg.add("参数错误");
        }


        if (errormsg != null && errormsg.size() > 0) {
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, JSON.toJSONString(errormsg));
        }
        BusinessTeacherInfo teacherInfo = teacherInfoService.findByTeacherId(teacherId);
        if (teacherInfo != null && teacherInfo.getGroupId() != null && 1 == deptFullName.intValue()) {
            teacherInfo.setDeptFullName(miniAdminService.getDeptFullName(teacherInfo.getGroupId()));
        }
        if (teacherInfo != null) {
            teacherInfo.setWechatInfos(teacherWechatInfoService.findWechatListByTeacherId(teacherInfo.getTeacherId(), useType));
        }

        return BusinessResult.createSuccessInstance(teacherInfo);
    }

    @CheckLogin
    @GetMapping("/canUse/{teacherId}")
    @ApiOperation(value = "查询专员信息，只包含启用的微信", notes = "查询专员信息，只包含启用的微信")
    public BusinessResult<BusinessTeacherInfo> canUseTeacherInfo(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                                                 @ApiParam(value = "运营专员id", required = true) @PathVariable Long teacherId,
                                                                 @ApiParam(value = "运营专员id", required = false, defaultValue = "0")
                                                                 @RequestParam(required = false, defaultValue = "0") Integer deptFullName) {

        BusinessTeacherInfo teacherInfo = teacherInfoService.findByTeacherId(teacherId);
        if (teacherInfo != null && teacherInfo.getGroupId() != null && 1 == deptFullName.intValue()) {
            teacherInfo.setDeptFullName(miniAdminService.getDeptFullName(teacherInfo.getGroupId()));
        }
        if (teacherInfo != null) {
            teacherInfo.setWechatInfos(teacherWechatInfoService.findCanUseWechatByTeacherId(teacherInfo.getTeacherId(), null));
        }

        return BusinessResult.createSuccessInstance(teacherInfo);
    }

    @GetMapping("/info")
    @ApiOperation(value = "查询专员信息-内部调用,只查询可用的微信", notes = "查询专员信息-内部调用，只查询可用的微信")
    public BusinessResult<BusinessTeacherInfo> info(@RequestHeader String sig,
                                                    @RequestParam Long teacherId) {

        BusinessTeacherInfo teacherInfo = teacherInfoService.findByTeacherId(teacherId);
        if (teacherInfo == null) {
            return BusinessResult.createInstance(CommonResultMessage.NO_TEACHER_INFO);
        }
        teacherInfo.setWechatInfos(teacherWechatInfoService.findCanUseWechatByTeacherId(teacherId, null));
        return BusinessResult.createSuccessInstance(teacherInfo);
    }


    @GetMapping("/findTeacherByWxId")
    public BusinessResult<BusinessTeacherInfo> findTeacherByWxId(@ApiParam(value = "签名信息", required = true) @RequestHeader String sig,
                                                                 @RequestParam String wxId) {

        if (!(checkSign(sig))) {
            return BusinessResult.createInstance(CommonResultMessage.SIGN_ERROR);
        }
        BusinessTeacherInfo teacherInfo = null;
        BusinessTeacherWechatInfo teacherWechatInfo = teacherWechatInfoService.findByWxNo(wxId);
        if (teacherWechatInfo != null) {
            teacherInfo = teacherInfoService.findByTeacherId(teacherWechatInfo.getTeacherId());
        }
        return BusinessResult.createSuccessInstance(teacherInfo);
    }

    //禁用启用wehub相关内容
    private void enableOrdisableWehubAbout(Integer states, Long teacherId, Long operateUser, String loginWxId, String wechatNo) {
        try {
//            FriendRemarkUserStateVO friendRemarkUserStateVO = new FriendRemarkUserStateVO();
//            friendRemarkUserStateVO.setOperateUser(operateUser);
//            friendRemarkUserStateVO.setUserId(teacherId);
//            friendRemarkUserStateVO.setWxId(wechatNo);
            if (states.equals(1)) {
                //禁用wehub登陆
                wehubAdminServer.disableWechat(sign, teacherId, loginWxId, wechatNo);
                //禁用自动回复
//                friendRemarkUserStateVO.setUseState(0);
//                wehubAdminServer.forbiddenRemarkConfig(sign,friendRemarkUserStateVO);
            } else {
//                friendRemarkUserStateVO.setUseState(1);
//                wehubAdminServer.forbiddenRemarkConfig(sign,friendRemarkUserStateVO);
            }

        } catch (Exception ex) {

        }
    }


    @GetMapping("/findCorpWxInfoByTeacherId")
    public BusinessResult<BusinessTeacherWechatInfo> findCorpWxInfoByTeacherId(@RequestHeader String sig, @RequestParam Long teacherId) {

        if (!(checkSign(sig))) {
            return BusinessResult.createInstance(CommonResultMessage.SIGN_ERROR);
        }
        BusinessTeacherWechatInfo teacherWechatInfo = teacherWechatInfoService.findCorpWxInfoByTeacherId(teacherId);
        return BusinessResult.createSuccessInstance(teacherWechatInfo);
    }

    @CheckLogin
    @PostMapping("/bingCorpWxInfo")
    @ApiOperation(value = "绑定企业微信", notes = "绑定企业微信")
    public BusinessResult<BusinessTeacherWechatInfo> bingCorpWxInfo(@RequestHeader String Authorization,
                                                                    @RequestBody CorpWxInfoREQ corpWxInfoREQ

    ){
        log.info("bingCorpWxInfo params = {} ", JSON.toJSONString(corpWxInfoREQ));
        List<String> errormsg = new ArrayList<>();
        String corpUserId = corpWxInfoREQ.getCorpUserId();
        String corpNewUserId = corpWxInfoREQ.getCorpNewUserId();
        Long teacherId = corpWxInfoREQ.getTeacherId();
        String corpUserQrUrl = corpWxInfoREQ.getCorpUserQrUrl();
        String teacherPhoneNum = corpWxInfoREQ.getTeacherPhoneNum();
        Integer states = corpWxInfoREQ.getStates();
        String corpName = corpWxInfoREQ.getCorpName();
        String corpId = corpWxInfoREQ.getCorpId();
        String corpUserName = corpWxInfoREQ.getCorpUserName();

        if(StringUtils.isBlank(teacherPhoneNum) || !(MatcherRule.isMobileNO(teacherPhoneNum))){
            errormsg.add("teacherPhoneNum 值错误");
        }
        if(StringUtils.isBlank(corpUserQrUrl)){
            errormsg.add("corpUserQrUrl 为空");
        }
        if(StringUtils.isBlank(corpUserId)){
            errormsg.add("corpUserId 为空");
        }
        if(StringUtils.isBlank(corpId)){
            errormsg.add("corpId 为空");
        }
        if(StringUtils.isBlank(corpName)){
            errormsg.add("corpName 为空");
        }
        if(StringUtils.isBlank(corpUserName)){
            errormsg.add("corpUserName 为空");
        }
        if(StringUtils.isBlank(corpNewUserId)){
            errormsg.add("corpNewUserId 为空");
        }
        if(teacherId.intValue() == 0){
            errormsg.add("teacherId 值错误");
        }
        if(states == null ){
            errormsg.add("states 值错误");
        }
        if( corpWxInfoREQ.getUseType() == null ){
            errormsg.add("userType 值错误");
        }

        if(errormsg !=null && errormsg.size() > 0){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, JSON.toJSONString(errormsg));
        }

        Long wxNoUseStates = teacherWechatInfoService.countByCorpUserIdAndTeacherIdNot(corpUserId, teacherId);
        if(wxNoUseStates != null && wxNoUseStates.intValue() > 0){
            errormsg.add("该企业账号【"+ corpUserName +"】已经绑定了飞天账号");
        }
        if(errormsg !=null && errormsg.size() > 0){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, JSON.toJSONString(errormsg));
        }
        if(!(corpUserId.equalsIgnoreCase(corpNewUserId))){
            Long wxNewNoUseStates = teacherWechatInfoService.countByCorpUserIdAndTeacherIdNot(corpNewUserId, teacherId);
            if(wxNewNoUseStates != null && wxNewNoUseStates.intValue() > 0){
                errormsg.add("该企业账号【"+ corpUserName +"】已经绑定了飞天账号");
            }
        }
        if(errormsg !=null && errormsg.size() > 0){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, JSON.toJSONString(errormsg));
        }

        BusinessTeacherInfo teacherInfo = teacherInfoService.findByTeacherId(teacherId);
        if(teacherInfo == null){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR,"运营专员信息不存在");
        }

        teacherInfoService.saveCorpWechat(teacherInfo,corpWxInfoREQ);
        return BusinessResult.createSuccessInstance(null);
    }

    @GetMapping("/wehub/{teacherId}")
    @ApiOperation(value = "可以在wehub使用的微信，不区分状态", notes = "可以在wehub使用的微信，不区分状态")
    public BusinessResult<BusinessTeacherInfo> wehubCanUseWechat(@RequestHeader String sig, @PathVariable Long teacherId) {

        if (!(checkSign(sig))) {
            return BusinessResult.createInstance(CommonResultMessage.SIGN_ERROR);
        }

        BusinessTeacherInfo teacherInfo = teacherInfoService.findByTeacherId(teacherId);

        if (teacherInfo != null) {
            teacherInfo.setWechatInfos(teacherWechatInfoService.findWehubCanUseWechatByTeacherId(teacherInfo.getTeacherId()));
        }

        return BusinessResult.createSuccessInstance(teacherInfo);
    }

    @CheckLogin
    @ApiOperation(value = "运营专员裂变-分页", notes = "运营专员裂变-分页")
    @PostMapping("/pageTeacher")
    public BusinessResult<PageResultVO<BusinessTeacherInfo>> pageTeacher(@RequestHeader String Authorization,
                                                                         @RequestBody TeacherCondition condition) {
        condition.setStates(0);
        PageResultVO<BusinessTeacherInfo> page = teacherInfoService.page(condition);
        return BusinessResult.createSuccessInstance(page);

    }


    @CheckLogin
    @ApiOperation(value = "通过微信号查询微信信息", notes = "通过微信号查询微信信息",hidden = true)
    @GetMapping(value = "/findByTeacherWxNo")
    public BusinessResult findByTeacherWxNo(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                            @RequestParam String teacherWxNo) {
        JSONObject result = new JSONObject();
        BusinessTeacherWechatInfo teacherWechatInfo = teacherWechatInfoService.findByWxNo(teacherWxNo);
        if (teacherWechatInfo != null) {
            Long teacherId = teacherWechatInfo.getTeacherId();
            BusinessTeacherInfo teacherInfo = teacherInfoService.findByTeacherId(teacherId);
            result.put("deptFullName", teacherInfo.getSkuName() + "-" + teacherInfo.getWorkRoomName() + "-" + teacherInfo.getDeptName() + "-" + teacherInfo.getGroupName());
            result.put("teacherId", teacherId);
            result.put("teacherName", teacherWechatInfo.getTeacherName());
            result.put("teacherWxNo", teacherWechatInfo.getWxNo());
            result.put("teacherWxQrUrl", teacherWechatInfo.getWxQrUrl());
            result.put("teacherPhone", teacherWechatInfo.getPhone());
            result.put("wechatType", teacherWechatInfo.getUseType());
            result.put("corpName", teacherWechatInfo.getCorpName());
            result.put("corpUserName", teacherWechatInfo.getCorpUserName());
            result.put("corpUserQrUrl", teacherWechatInfo.getCorpUserQrUrl());
        }
        return BusinessResult.createSuccessInstance(result);
    }

    @ApiOperation(value = "mini-business同步微信数据",hidden = true)
    @PostMapping("/syncWechatInfo")
    public BusinessResult<Void> syncWechatInfo(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,@RequestBody BusinessTeacherWechatInfo wechatInfo) {
        teacherWechatInfoService.save(wechatInfo);
        return BusinessResult.createSuccessInstance(null);
    }


    @ApiOperation(value = "同步接待量数据")
    @PostMapping("/synDataAddWechatNumALl")
    public BusinessResult<Void> synDataAddWechatNumALl(@ApiParam(value = "token", required = true) @RequestHeader String Authorization) {
        teacherInfoService.synDataAddWechatNumALl();
        return BusinessResult.createSuccessInstance(null);
    }


}
